package com.ccb.sc.common.modules.member.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccb.sc.common.modules.live.enums.LiveStreamingOrderExchangeStatus;
import com.ccb.sc.common.modules.live.service.LiveStreamingReserveService;
import com.ccb.sc.common.modules.member.entity.MemberMedal;
import com.ccb.sc.common.modules.member.mapper.MemberMedalMapper;
import com.ccb.sc.common.modules.order.entity.OrderExchange;
import com.ccb.sc.common.modules.order.service.impl.OrderExchangeService;
import com.ccb.sc.common.rule.medal.fact.MedalFact;
import com.ccb.sc.common.rule.medal.rules.AbstractMedalRule;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 会员勋章 服务实现类
 * </p>
 *
 * @author ken
 * @since 2022-07-30
 */
@Service
public class MemberMedalService extends ServiceImpl<MemberMedalMapper, MemberMedal> {

    @Autowired
    private List<AbstractMedalRule> rules;

    @Autowired
    private OrderExchangeService orderExchangeService;

    @Autowired
    private LiveStreamingReserveService liveStreamingService;

    @Async
    public void executeRule(Long memberId) {
        long exchangeOrders = this.orderExchangeService.count(Wrappers.<OrderExchange>lambdaQuery()
                .eq(OrderExchange::getMemberId, memberId)
                .eq(OrderExchange::getExchangeStatus, LiveStreamingOrderExchangeStatus.FINISHED));

        int reserves = this.liveStreamingService.selectReserveCount(memberId);

        Facts facts = new Facts();
        MedalFact medalFact = new MedalFact();
        medalFact.setMemberId(memberId);
        medalFact.setExchangeOrders((int) exchangeOrders);
        medalFact.setResevers(reserves);
        facts.put("fact", medalFact);

        RulesEngine rulesEngine = new DefaultRulesEngine();

        Rules rules = new Rules();
        for (AbstractMedalRule rule : this.rules) {
            rules.register(rule);
        }

        rulesEngine.fire(rules, facts);
    }
}
